﻿using Microsoft.Extensions.DependencyInjection;
using Modules.CheckInCount.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.CheckInCount.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CountPermonthRepository : Repository<CountPermonth, CheckinDbContext>
    {
        public CountPermonthRepository(CheckinDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        /// <summary>
        /// 获取指定条件每月统计集合
        /// </summary>
        /// <param name="tenantType"></param>
        /// <param name="countType"></param>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="objectIds"></param>
        /// <returns></returns>
        public IEnumerable<CountPermonth> GetCountPermonths(CountTenantType tenantType, CountType countType, int year, int month, IEnumerable<int> objectIds)
        {
            if (objectIds == null || objectIds.Count() == 0)
                return Enumerable.Empty<CountPermonth>();

            string tableName = GetTableName(tenantType, countType);
            Sql sql = Sql.Builder;
            sql.Select("*")
                .From(tableName)
                .Where("year=@0 AND month=@1 AND object_id IN(@2)", year, month, objectIds);

            return DbContext.Fetch<CountPermonth>(sql);
        }

        /// <summary>
        /// 获取表名
        /// </summary>
        /// <param name="tenantType"></param>
        /// <param name="countType"></param>
        /// <returns></returns>
        private string GetTableName(CountTenantType tenantType, CountType countType)
        {
            return $"{tenantType}_{countType}_permonth".ToLower();
        }
    }
}